package com.woorigil.social.parser.wemakeprice;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.json.JSONObject;
import org.jsoup.Jsoup;

import com.woorigil.social.HttpUtils;
import com.woorigil.social.domain.ProviderCode;

public class TourSiteParser {
	String baseUrl = "http://www.wemakeprice.com/main/get_deal_more/${}?_=1374058303003&curr_deal_cnt=0&r_cnt=5000";
	
	static Map<Integer, List<String>> siteUrls = new HashMap<Integer, List<String>>() {{
		put(35, Arrays.asList("990100"));
		put(36, Arrays.asList("990600"));
		put(37, Arrays.asList("990200"));
		put(38, Arrays.asList("990300", "991200", "990400", "991300"));
		put(39, Arrays.asList("990500"));
	}};	

	private WemakeExtraDeal extractDealInfo(org.jsoup.nodes.Element element, int categoryId, org.jsoup.select.Elements td1s) {
		String metaId = element.attr("deal_id");
		String imageUrl = element.select(".box_thumb img").attr("original");
		return new WemakeExtraDeal(ProviderCode.WM, metaId, imageUrl, categoryId);
	}
	
	public Map<String, WemakeExtraDeal> parse() {
		Map<String, WemakeExtraDeal> extraDeals = new HashMap<String, WemakeExtraDeal>();
		for (Entry<Integer, List<String>> entry : siteUrls.entrySet()) {
			for (String each : entry.getValue()) {
				try {
					String data = HttpUtils.execute(baseUrl.replace("${}", each));
					String html = new JSONObject(data).getString("html");
					org.jsoup.nodes.Document doc = Jsoup.parse(html);
					org.jsoup.select.Elements td1s = doc.select("li");
					
					for (org.jsoup.nodes.Element element : td1s) {
						WemakeExtraDeal extraDeal = extractDealInfo(element, entry.getKey(), td1s);
						extraDeals.put(extraDeal.getMetaId(), extraDeal);
					}
				} catch (Exception e) {
				}
			}
		}
		return extraDeals;
	}
}
